﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Launcher
{
    class Program
    {
        static readonly string _temp = Path.Combine(Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User), "piano_transcription_helper");
        [DllImport("user32.dll")]
        static extern int MessageBoxA(IntPtr hwnd, string text, string caption, uint type);
        static void Main(string[] args)
        {
            if (!CheckPython())
            {
                var result = MessageBoxA(IntPtr.Zero, "未安装python，是否前往windows商店安装？", "错误", 1);
                if (result == 1) GoToStoreForPython();
                return;
            }
            ReleasePys();
            StartApp();
            CleanTemp();
        }
        static void StartApp()
        {
            var p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = "python",
                    Arguments = Path.Combine(_temp, "main.pyw"),
                    CreateNoWindow = true,
                    UseShellExecute = false
                }
            };
            p.Start();
            p.WaitForExit();
        }
        static void ReleasePys()
        {
            Directory.CreateDirectory(_temp);
            Stream getFile(string name) => Assembly.GetExecutingAssembly().GetManifestResourceStream("Launcher.pys." + name);

            var mainPath = Path.Combine(_temp, "main.pyw");
            var mainFile = File.Open(mainPath, FileMode.Create);
            using(var file = getFile("main.pyw"))
            {
                file.CopyTo(mainFile);
                mainFile.Close();
                file.Close();
            }

            Directory.CreateDirectory(Path.Combine(_temp, "piano_transcription_inference_modified"));
            var files = new List<string>()
            {
                "__init__.py",
                "config.py",
                "crash.py",
                "inference.py",
                "models.py",
                "piano_vad.py",
                "pytorch_utils.py",
                "utilities.py"
            };
            foreach (var fileName in files)
            {
                var path = Path.Combine(_temp, "piano_transcription_inference_modified", fileName);
                var file = File.Open(path, FileMode.Create);
                var data = getFile(fileName);
                data.CopyTo(file);
                file.Close();
                data.Close();
            }

            Directory.CreateDirectory(Path.Combine(_temp, "windnd"));
            var files2 = new List<string>()
            {
                "__init__.py",
                "windnd.py"
            };
            foreach (var fileName in files2)
            {
                var path = Path.Combine(_temp, "windnd", fileName);
                var file = File.Open(path, FileMode.Create);
                var data = getFile("windnd." + fileName);
                data.CopyTo(file);
                file.Close();
                data.Close();
            }
        }
        static void CleanTemp() => Directory.Delete(_temp, true);
        static bool CheckPython()
        {
            var p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = "python",
                    Arguments = "--version"
                }
            };
            p.Start();
            p.WaitForExit();
            if (p.ExitCode == 0) return true;
            else return false;
        }
        static void GoToStoreForPython()
        {
            var p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = "powershell",
                    Arguments = "start ms-windows-store://pdp/?ProductId=9p7qfqmjrfp7",
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
            p.Start();
            p.WaitForExit();
        }
    }
}
